from classify.classify import Classify
import logging
import logging.config
import sys
import yaml
from flask import Flask
from flask_restful import Api
import api.img as img
from querier.img.img_search import ImgSearchQuerier
from querier.img.img_sim import ImgSimQuerier
from querier.img.img_info import ImgInfoQuerier
from elasticsearch import Elasticsearch
from querier.img.get_img import ImageHBASEQuerier
from flask_cors import CORS


def set_logging(conf_file):
    conf = load_yaml(conf_file)
    logging.config.dictConfig(conf)


def load_yaml(yaml_file):
    with open(yaml_file, 'r') as infile:
        config = yaml.load(infile)
    return config


def load_app(config_file, logging_config_file):
    app = Flask(__name__)
    api = Api(app)
    CORS(app)

    # config_file = 'config/config.yml'
    # logging_config_file = 'config/logging.yml'

    set_logging(logging_config_file)

    config = load_yaml(config_file)

    model_path = config['classifier']['MODEL_PATH']
    label_path = config['classifier']['LABEL_PATH']
    uid_path = config['classifier']['UID_PATH']
    # num_top_prediction = conf['classifier']['NUM_TOP_PREDICTION']

    timeout = config['es_config']['timeout']
    hosts = config['es_config']['hosts']
    es = Elasticsearch(hosts, timeout=timeout)

    indices = config['indices']

    classifier = Classify(model_path, label_path, uid_path)

    img_search_querier = ImgSearchQuerier(es, indices['image_search']['index'],
                                          indices['image_search']['doc_type'], classifier)

    img.ImageSearchResource.set_resource(parser=img.img_search_parser, post_querier=img_search_querier)

    img_sim_querier = ImgSimQuerier(classifier)
    img.ImageSimilarityResource.set_resource(parser=img.img_search_parser, post_querier=img_sim_querier)

    get_image_querier = ImageHBASEQuerier(config['hbase']['host'], config['hbase']['table'])

    img.ImageGetResource.set_resource(get_querier=get_image_querier)

    img_info_querier = ImgInfoQuerier()
    img.ImageInfoResource.set_resource(parser=img.img_info_parser, post_querier=img_info_querier)

    endpoints = config['endpoints']
    api.add_resource(img.ImageSearchResource, endpoints['search_image'])
    api.add_resource(img.ImageGetResource, endpoints['get_image'])
    api.add_resource(img.ImageSimilarityResource, endpoints['similarity'])
    api.add_resource(img.ImageInfoResource, endpoints['image_info'])
    return app


if __name__ == '__main__':
    conf_file = ''
    logging_conf_file = ''
    if len(sys.argv) < 2:
        print('Usage: python3.4 start_api.py <config.yaml> <logging.yaml>')
        exit(1)
    else:
        conf_file = sys.argv[1]
        logging_conf_file = sys.argv[2]

    config = load_yaml(conf_file)

    app = load_app(conf_file, logging_conf_file)
    app.run(**config["app_serve"])
